package com.sz.sidi.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.springframework.util.FileCopyUtils;

import com.sz.sidi.exceptions.DaoException;


/**
 * @author DT E-mail: dengtao@chinacpby.com
 * @version ����ʱ�䣺Jun 5, 2009 6:00:00 PM
 */
public class GlobalFun {

	protected static java.text.DecimalFormat df = new java.text.DecimalFormat(
			"#.##");
	protected static Logger logger = Logger.getLogger(GlobalFun.class);

	private static final NumberFormat numberFormater = NumberFormat
	.getNumberInstance();
	
	public static String getErrCauseMsg(Exception e, Class errCls) {
		if (e == null)
			return "";
		Throwable e1 = (Throwable) e.getCause();
		if (e1 == null)
			return e.getMessage();
		return e1.getMessage();
	}

	public static String getErrCauseMsg(Exception e) {
		if (e == null)
			return "";
		Throwable e1 = (Throwable) e.getCause();
		if (e1 == null)
			return e.getMessage();
		return e1.getMessage();
	}

	/**
	 * 
	 * 判断传入参数是否有效
	 */
	public static boolean hasValue(String s) {
		return ((s != null) && (s.trim().length() > 0));
	}

	public static boolean hasValue(Integer i) {
		return ((i != null) && (i.intValue() > 0));
	}

	public static boolean hasValue(Long i) {
		return ((i != null) && (i.intValue() > 0));
	}

	public static boolean hasValue(Double i) {
		return ((i != null) && (i.doubleValue() > 0));
	}

	/**
	 * 方法开始时打印
	 */
	public static void logIn() {
//		Exception e = new Exception();
//
//		try {
//			logger.info(TimeHelper.getCurrentTimeString()
//					+ " 开始方法："
//					+ Class.forName(e.getStackTrace()[1].getClassName())
//							.getSimpleName() + "#"
//					+ e.getStackTrace()[1].getMethodName());
//		} catch (Exception e1) {
//			e1.printStackTrace();
//		}

	}

	/**
	 * 方法结束时打印
	 */
	public static void logOut() {
//		Exception e = new Exception();
//		try {
//			logger.info(TimeHelper.getCurrentTimeString()
//					+ " 结束方法："
//					+ Class.forName(e.getStackTrace()[1].getClassName())
//							.getSimpleName() + "#"
//					+ e.getStackTrace()[1].getMethodName());
//		} catch (Exception e1) {
//			e1.printStackTrace();
//		}
	}

	/**
	 * @param file
	 * @return
	 * @throws IOException
	 *             File转换到byte[]
	 */
	public static byte[] fileToByte(File file) throws IOException {
		byte[] bytes = null;
		if (file != null) {
			bytes = FileCopyUtils.copyToByteArray(file);
		}
		return bytes;
	}

	/**
	 * @param btyes
	 * @param file
	 * @throws IOException byte[]转换到File
	 */
	public static void byteToFile(byte[] btyes, File file) throws IOException {
		if (file != null) {
			if (!file.exists()) {
				file.createNewFile();
			}
			FileCopyUtils.copy(btyes, file);
		}
	}

	/**
	 * 验证是否为Integer
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateInteger(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Integer(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Long
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateLong(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Long(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Float
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateFloat(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Float(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Double
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateDouble(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Double(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Date，格式yyyy-MM-dd
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateDate(String value) {
		return validateDate(value, "yyyy-MM-dd");
	}

	/**
	 * 验证是否为Date，格式yyyy-MM-dd HH:mm:ss
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateTime(String value) {
		return validateDate(value, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 验证是否为Boolean
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateBoolean(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Boolean(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为空
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateRequired(String value) {
		if (value == null || value.equals(""))
			return false;
		else
			return true;
	}

	/**
	 * 验证最大长度
	 * 
	 * @param value
	 * @param length
	 * @return
	 */
	public static boolean validateMaxLength(String value, int length) {
		if (value == null)
			return false;
		if (value.length() > length)
			return false;
		return true;
	}

	/**
	 * 根据正则表达式验证
	 * 
	 * @param value
	 * @param pattern
	 * @return
	 */
	public static boolean validateMask(String value, String pattern) {
		if (value == null)
			return false;
		Pattern pt = Pattern.compile(pattern);
		return pt.matcher(value).matches();
	}

	/**
	 * 验证日期
	 * 
	 * @param pattern
	 * @param string
	 * @return
	 */
	public static boolean validateDate(String value, String pattern) {
		if (value == null || value.equals(""))
			return false;
		if (value.length() != pattern.length())
			return false;
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		format.setLenient(false);
		try {

			format.parse(value);
		} catch (ParseException e) {
			return false;
		}
		return true;
	}

	// 对前后没有引号的字符串添加引号
	public static String Addquotes(String str) {
		if (str != null) {
			if (!str.startsWith("'"))
				return quotedStr(str);
			else
				return str;
		} else
			return "''";
	}

	/**
	 * 将字符串用引号括起来,适用于SQL拼装
	 * 
	 * @param str
	 * @return
	 */
	public static String quotedStr(String str) {
		if (str != null)
			return "'".concat(str).concat("'");
		else
			return "''";
	}
	
	public static void main(String[] args) {
		System.out.println(quotedStr(""));
	}

	/**
	 * @param conn
	 * @param stat
	 * @param rs
	 * @throws SQLException
	 *             关闭数据库资源
	 */
	public static void closeDataBaseResource(Connection conn, Statement stat,
			ResultSet rs) throws DaoException {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (stat != null) {
				stat.close();
				stat = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			throw new DaoException(e.getMessage());
		}

	}

	// 新增内容：
	public static String[] getModelFieldValue(Object obj, String[] columns)
			throws DaoException {
		if (obj == null) {
			logger.error("obj is null!");
			return new String[0];
		}
		String[] result;
		if (obj instanceof Map) {
			Map map = (Map) obj;
			// Set set=map.keySet();
			Collection set = map.values();
			result = new String[map.size()];
			Iterator iterator = set.iterator();
			int index = 0;
			while (iterator.hasNext()) {
				Object fValue = iterator.next();
				result[index] = getStringValue(fValue);
				// result[index] = String.valueOf(iterator.next());
				index++;
			}
			return result;
		}

		if (obj instanceof Object[]) {
			Object[] objs = (Object[]) obj;
			int l = getModelFieldSize(obj);
			result = new String[l];
			int id = 0;
			for (int i = 0; i < objs.length; i++) {
				String[] objValus = getModelFieldValue(objs[i], columns);
				for (int j = 0; j < objValus.length; j++) {
					result[id] = objValus[j];
					id++;
				}
			}
			return result;
		}

		// Class cls = obj.getClass();
		// Field fieldlist[] = cls.getDeclaredFields();
		// if (fieldlist.length <= 0) {
		// logger.error("对象:[" + cls.getName() + "]字段为空!");
		// return new String[0];
		// }
		// int fSize = getModelFieldSize(obj);
		result = new String[columns.length];
		int j = 0;
		for (int i = 0; i < columns.length; i++) {

			try {
				Object fValue = null;
				if (!columns[i].equals("")) {
					fValue = PropertyUtils.getSimpleProperty(obj,
							columns[i]);
				}
				if (fValue == null) {
					result[i + j] = String.valueOf(fValue);
					continue;
				}
				String fTypeName = fValue.getClass().getName();
				if (fTypeName.indexOf("com.ztkj") >= 0) {
					String[] sFValue = getModelFieldValue(fValue, columns);
					if (sFValue.length > 0) {
						System.arraycopy(sFValue, 0, result, i, sFValue.length);
						j = j + sFValue.length - 1;
						continue;
					}
				}

				String strValue = null;
				if (fValue instanceof byte[]) {
					try {
						strValue = byteArr2HexStr((byte[]) fValue);
					} catch (Exception e) {
						e.printStackTrace();
						throw new DaoException(
								"method<getModelFieldValue>:Blob转换异常！"
										+ e.getMessage());
					}
				} else if (fValue instanceof short[])
					strValue = Formate.TransformAS((short[]) fValue);
				else
					strValue = String.valueOf(fValue);
				result[i + j] = strValue;
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				throw new DaoException("method<getModelFieldValue>:非法访问"
						+ e.getMessage());
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				throw new DaoException("method<getModelFieldValue>:非法目标"
						+ e.getMessage());
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
				throw new DaoException("method<getModelFieldValue>:方法不存在"
						+ e.getMessage());
			}
		}
		return result;
	}

	// 新增内容：
	public static String[] getModelFieldValue(Object obj) throws Exception {
		if (obj == null) {
			return new String[0];
		}
		String[] result;
		if (obj instanceof Map) {
			Map map = (Map) obj;
			// Set set=map.keySet();
			Collection set = map.values();
			result = new String[map.size()];
			Iterator iterator = set.iterator();
			int index = 0;
			while (iterator.hasNext()) {
				Object fValue = iterator.next();
				result[index] = getStringValue(fValue);
				// result[index] = String.valueOf(iterator.next());
				index++;
			}
			return result;
		}

		if (obj instanceof Object[]) {
			Object[] objs = (Object[]) obj;
			int l = getModelFieldSize(obj);
			result = new String[l];
			int id = 0;
			for (int i = 0; i < objs.length; i++) {
				String[] objValus = getModelFieldValue(objs[i]);
				for (int j = 0; j < objValus.length; j++) {
					result[id] = objValus[j];
					id++;
				}
			}
			return result;
		}

		Class cls = obj.getClass();
		Field fieldlist[] = cls.getDeclaredFields();
		if (fieldlist.length <= 0) {
			return new String[0];
		}
		int fSize = getModelFieldSize(obj);
		result = new String[fSize];
		int j = 0;
		for (int i = 0; i < fieldlist.length; i++) {
			Field fld = fieldlist[i];
			String fieldName = fld.getName();
			try {
				Object fValue = PropertyUtils.getSimpleProperty(obj, fieldName);
				if (fValue == null) {
					result[i + j] = String.valueOf(fValue);
					continue;
				}
				String fTypeName = fValue.getClass().getName();
				if (fTypeName.indexOf("com.ztkj") >= 0) {
					String[] sFValue = getModelFieldValue(fValue);
					if (sFValue.length > 0) {
						System.arraycopy(sFValue, 0, result, i, sFValue.length);
						j = j + sFValue.length - 1;
						continue;
					}
				}

				String strValue = null;
				if (fValue instanceof byte[]) {
					try {
						strValue = byteArr2HexStr((byte[]) fValue);
					} catch (Exception e) {
						e.printStackTrace();
						throw new Exception(
								"method<getModelFieldValue>:Blob转换异常！"
										+ e.getMessage());
					}
				} else if (fValue instanceof short[])
					strValue = Formate.TransformAS((short[]) fValue);
				else
					strValue = String.valueOf(fValue);
				result[i + j] = strValue;
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				throw new Exception("method<getModelFieldValue>:非法访问"
						+ e.getMessage());
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				throw new Exception("method<getModelFieldValue>:非法目标"
						+ e.getMessage());
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
				throw new Exception("method<getModelFieldValue>:方法不存在"
						+ e.getMessage());
			}
		}
		return result;
	}
	
	public static int getModelFieldSize(Object obj) throws DaoException {
		if (obj == null) {
			logger.error("Object is null!");
			return 0;
		}
		int l = 0;
		if ((obj instanceof Class[]) || (obj instanceof Class[])) {
			Class[] clss = null;

			if (obj instanceof Class[])
				clss = (Class[]) obj;
			else if (obj instanceof Object[]) {
				Object[] objs = (Object[]) obj;
				clss = new Class[objs.length];
				for (int i = 0; i < objs.length; i++)
					clss[i] = objs[i].getClass();
			}

			for (int i = 0; i < clss.length; i++)
				l = l + getModelFieldSize(clss[i]);
			return l;
		}

		if (obj instanceof Map)
			return ((Map) obj).size();

		Class cls;
		if (obj instanceof Class)
			cls = (Class) obj;
		else
			cls = obj.getClass();
		Field fieldlist[] = cls.getDeclaredFields();
		if (fieldlist.length <= 0) {
			// err("对象:[" + cls.getName() + "]字段为空!");
			return 0;
		}
		for (int i = 0; i < fieldlist.length; i++) {
			// if (fieldlist[i].getType().getSimpleName().equalsIgnoreCase(
			// "boolean"))
			// continue;
			String fTypeName = fieldlist[i].getType().getName();
			if (fTypeName.indexOf("com.ztkj") >= 0) {
				// System.out.println(fieldlist[i].getName());
				// System.out.println(fieldlist[i].getType());
				Field[] subfieldlist = fieldlist[i].getType()
						.getDeclaredFields();
				int il = subfieldlist.length;
				if (il > 0) {
					l = l + il;
					continue;
				}
			}
			l++;
		}
		// l = fieldlist.length;
		return l;
	}

	private static String getStringValue(Object fValue) throws DaoException {
		String strValue = null;
		if (fValue instanceof byte[]) {
			try {
				strValue = byteArr2HexStr((byte[]) fValue);
			} catch (Exception e) {
				e.printStackTrace();
				throw new DaoException("method<getModelFieldValue>:Blob转换异常！"
						+ e.getMessage());
			}
		} else if (fValue instanceof short[])
			strValue = Formate.TransformAS((short[]) fValue);
		else
			strValue = String.valueOf(fValue);
		return strValue;
	}

	public static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}
	
	/**
	 * 计算两个日期之间相差多少天(aNow-aThen)
	 * 
	 * @param lateDate
	 *            较晚时间
	 * @param earlyDate
	 *            较早时间
	 * @return 天数
	 */
	public static int daysBetween(Date lateDate, Date earlyDate) {
		long days = TimeHelper.daysBetweenDate(lateDate, earlyDate);
		return (int) days;
	}

	/**
	 * 计算两个日期之间相差多少月(aNow-aThen)
	 * 
	 * @param lateDate
	 *            较晚时间
	 * @param earlyDate
	 *            较早时间
	 * @return 月数
	 */
	public static int monthsBetween(Date lateDate, Date earlyDate) {
		long days = TimeHelper.daysBetweenDate(lateDate, earlyDate);
		int months = (int) (days / 30.4375);
		return months;
	}

	/**
	 * 计算两个日期之间相差多少年(aNow-aThen)
	 * 
	 * @param lateDate
	 *            较晚时间
	 * @param earlyDate
	 *            较早时间
	 * @return 年数
	 */
	public static int yearsBetween(Date lateDate, Date earlyDate) {
		long days = TimeHelper.daysBetweenDate(lateDate, earlyDate);
		int years = (int) (days / 365.25);
		return years;
	}
	
	public static Integer stringToInteger(String str) {
		if (null == str || "".equals(str.trim())) {
			return null;
		} else if (GlobalFun.validateInteger(str)) {
			return Integer.parseInt(str);
		} else {
			return null;
		}
	}

	public static Long stringToLong(String str) {
		if (str == null || "".equals(str)) {
			return null;
		} else if (GlobalFun.validateLong(str)) {
			return Long.parseLong(str);
		} else {
			return null;
		}
	}

	public static Double stringToDouble(String str) {
		if (str == null || "".equals(str)) {
			return null;
		} else if (GlobalFun.validateDouble(str)) {
			return Double.parseDouble(str);
		} else {
			return null;
		}
	}

	public static Float stringToFloat(String str) {
		if (str == null || "".equals(str)) {
			return null;
		} else if (GlobalFun.validateFloat(str)) {
			return Float.parseFloat(str);
		} else {
			return null;
		}
	}
	
	public static String numberToString(String str) {
		if (str == null) {
			return "";
		} else {
			return str.trim();
		}
	}

	public static String numberToString(Integer lg) {
		if (lg == null) {
			return "";
		} else {
			return lg + "";
		}
	}

	public static String numberToString(Long lg) {
		if (lg == null) {
			return "";
		} else {
			// try {
			// return
			// numberFormater.parse(numberFormater.format(lg).toString()).longValue()+"";
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			numberFormater.setGroupingUsed(false);
			return numberFormater.format(lg);
		}
	}

	public static String numberToString(Double db) {
		if (db == null) {
			return "";
		} else {
			numberFormater.setGroupingUsed(false);
			numberFormater.setMaximumFractionDigits(4);
			return numberFormater.format(db);
			// try {
			// return
			// numberFormater.parse(numberFormater.format(db).toString()).doubleValue()+"";
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			// return numberFormater+"";
		}
	}

	public static String numberToString(Float db) {
		if (db == null) {
			return "";
		} else {
			numberFormater.setGroupingUsed(false);
			return numberFormater.format(db);
			// try {
			// return
			// numberFormater.parse(numberFormater.format(db).toString()).floatValue()+"";
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			// return numberFormater+"";
		}
	}
	
	/**
	 * 判断一个字符串的类型 输入：判断字符串 返回： 如果字符串是数字，返回0， 如果字符串是字母，返回1， 如果字符串是汉字，返回2,
	 * 如果字符串为空,返回3 Author :yczyk
	 */
	public static int justAStrType(String sStr) {
		int iStart, result = 0;
		Boolean IsNumber = true, IsChar = true;
		int iLen = sStr.length();
		if (iLen == 0)
			result = 3;
		else {
			for (iStart = 0; iStart < iLen; iStart++) {
				if (IsNumber) {
					IsNumber = sStr.substring(iStart, iStart + 1).matches(
							"[0-9]");
					if (IsNumber)
						continue;
				}
				if (IsChar) {
					IsChar = sStr.substring(iStart, iStart + 1).matches(
							"[0-9a-zA-Z]");
					if (IsChar)
						continue;
				}
				if ((!IsNumber) && (!IsChar)) {
					result = 2;
					break;
				}
			}
			if (result != 2) {
				if ((IsNumber) && (IsChar))
					result = 0;
				else if (IsNumber)
					result = 0;
				else
					result = 1;
			}
		}
		return result;
	}
	
	  public static double getTwopoint(double p){
			try {
				return df.parse(df.format(p)).doubleValue();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return 0;
		}

  	  /**
		 * 将字符串的引号去掉
		 * 
		 * @param str
		 * @return
		 */
		public static String subquotedStr(String str) {
			if(str==null){
				return str;
			}
			return str.replace("'", "");
		}
		
		public static Integer disFormat(String preFix, String str) {
			if (!hasValue(str))
				return 0;
			int l = preFix.trim().length();
			if (l > str.length())
				return 0;
			String data = str.substring(l);
			Integer result = Integer.valueOf(data);
			return result;
		}
		public static String format(String preFix, Integer len, Integer number) {
			int l = len - preFix.trim().length();

			if (l > number.toString().length()) {
				return preFix + format(number, '0', l);
			} else {
				return preFix + number;
			}

		}
		public static String format(Integer number, char c, Integer len) {
			StringBuffer str = new StringBuffer();
			for (int i = 1; i <= len - number.toString().length(); i++)
				str.append(c);
			str.append(number);
			return str.toString();
		}
}
